// hooks/useAuth.ts
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

export const useAuth = () => {
  const navigate = useNavigate();

  const isLoggedIn = (): boolean => {
    const token = localStorage.getItem('__login__');
    if (!token) return false;

    // 检查 token 是否过期（假设 token 包含过期时间）
    try {
      const tokenData = JSON.parse(token);
      if (tokenData.expiresAt && Date.now() > tokenData.expiresAt) {
        return false;
      }
      return true;
    } catch {
      return false;
    }
  };

  const redirectToLogin = () => {
    // 清除无效的 token
    localStorage.removeItem('__login__');
    localStorage.removeItem('__login_info__');
    
    // 跳转到登录页
    navigate('/EconomicIndex', { replace: true });
  };

  const requireAuth = (): boolean => {
    if (!isLoggedIn()) {
      redirectToLogin();
      return false;
    }
    return true;
  };

  return {
    isLoggedIn,
    redirectToLogin,
    requireAuth
  };
};